Vue Convert Base64 to Image: To convert a base64 string to an image in Vue.js, you can use the btoa() method to decode the base64 string into binary data, and then create a new Blob object with the binary data and set the src attribute of an img element to the object URL of the blob. Alternatively, you can use the atob() method to decode the base64 string, convert it to a Uint8Array object, and use URL.createObjectURL() to create a blob URL, which can be assigned to the src attribute of an img element. The resulting image should be displayed in the img element.
How can I convert a Vue Base64 to image?
This Vue.js application allows users to convert a Base64 encoded string to an image. When the user inputs a Base64 string in the form, the watch property listens for changes in the base64Code property. Once there is a change, the convertBase64ToImage method is called, which creates an Image object and sets its src attribute to the Base64 string. The method also converts the Base64 string to a Blob object using the base64ToBlob method and creates a URL for the Blob using URL.createObjectURL. The created URL is then set as the imageUrl property, which is bound to the img tag in the template. The altText property is used as the alternate text for the image.
Vue Convert Base64 to Image Example
<div id="app">
<textarea v-model="base64Code"></textarea>
<div class="image-container" v-if="imageUrl">
<img :src="imageUrl" :alt="altText">
</div>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
base64Code: "",
imageUrl: null,
altText: "Sample Image"
};
},
watch: {
base64Code: function (val) {
if (val) {
this.imageUrl = this.convertBase64ToImage(val);
}
}
},
methods: {
convertBase64ToImage(base64) {
const image = new Image();
image.src = base64;
return URL.createObjectURL(this.base64ToBlob(base64));
},
base64ToBlob(base64) {
const byteString = atob(base64.split(',')[1]);
const mimeString = base64.split(',')[0].split(':')[1].split(';')[0];
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: mimeString });
}
}
});
</script>
Output of Vue Convert Base64 to Image



